import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_url.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import 'package:gallery_media_picker/gallery_media_picker.dart';
import 'package:mobkit_dashed_border/mobkit_dashed_border.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:animated_digit/animated_digit.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/blueprint/challenge_model.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/parts/login_required_dialog.dart';

/// 挑战详情页面视图模型
class QuestDetailNavigatorViewModel extends BaseViewModel {
  QuestModel? _currentQuest;
  QuestAttemptModel? _activeAttempt;
  DateTime? _chronometerStart;
  Duration _elapsedDuration = Duration.zero;
  String? _startImagePath;
  String? _endImagePath;
  bool _isTimerRunning = false;
  Timer? timer;
  List<QuestModel> _questList = [];

  /// 获取当前挑战
  QuestModel? get currentQuest => _currentQuest;

  /// 获取当前尝试
  QuestAttemptModel? get activeAttempt => _activeAttempt;

  /// 获取计时器开始时间
  DateTime? get chronometerStart => _chronometerStart;

  /// 获取已用时间
  Duration get elapsedDuration => _elapsedDuration;

  /// 获取开始图片路径
  String? get startImagePath => _startImagePath;

  /// 获取结束图片路径
  String? get endImagePath => _endImagePath;

  /// 检查是否有正在进行的挑战
  bool get hasActiveQuest =>
      _activeAttempt != null && !_activeAttempt!.isCompleted;

  /// 获取挑战在列表中的索引
  int getQuestIndex(String questId) {
    for (int i = 0; i < _questList.length; i++) {
      if (_questList[i].id == questId) {
        return i;
      }
    }
    return 0; // 如果找不到，返回默认值
  }

  /// 检查计时器是否运行中
  bool get isTimerRunning => _isTimerRunning;

  /// 初始化挑战详情
  void initializeQuestDetail(String questId) {
    // 获取挑战列表
    _questList = appState.questManager.quests;

    _currentQuest = appState.questManager.fetchQuestById(questId);
    _loadExistingAttempt();
    notifyListeners();
  }

  /// 加载现有尝试
  void _loadExistingAttempt() {
    if (_currentQuest != null) {
      final existingAttempts = appState.questManager.retrieveUserAttempts(
        'current_user',
      );

      // 首先查找未完成的挑战
      final activeAttempt = existingAttempts.firstWhere(
        (attempt) =>
            attempt.questId == _currentQuest!.id && !attempt.isCompleted,
        orElse:
            () => QuestAttemptModel(
              id: '',
              questId: '',
              userId: '',
              startTime: DateTime.now(),
            ),
      );

      if (activeAttempt.id.isNotEmpty) {
        // 有未完成的挑战
        _activeAttempt = activeAttempt;
        _startImagePath = activeAttempt.startImage;
        _endImagePath = activeAttempt.endImage;
        _chronometerStart = activeAttempt.startTime;
        _isTimerRunning = true;
        _updateElapsedTime();
        startTimer(); // 启动计时器
      } else {
        // 查找已完成的挑战
        final completedAttempt = existingAttempts.firstWhere(
          (attempt) =>
              attempt.questId == _currentQuest!.id && attempt.isCompleted,
          orElse:
              () => QuestAttemptModel(
                id: '',
                questId: '',
                userId: '',
                startTime: DateTime.now(),
              ),
        );

        if (completedAttempt.id.isNotEmpty) {
          // 有已完成的挑战，显示完成状态
          _activeAttempt = completedAttempt;
          _startImagePath = completedAttempt.startImage;
          _endImagePath = completedAttempt.endImage;
          _chronometerStart = completedAttempt.startTime;
          _isTimerRunning = false; // 已完成，不运行计时器
          _elapsedDuration = completedAttempt.duration ?? Duration.zero;
        }
      }
    }
  }

  /// 更新已用时间
  void _updateElapsedTime() {
    if (_chronometerStart != null && _isTimerRunning) {
      _elapsedDuration = DateTime.now().difference(_chronometerStart!);
    }
  }

  /// 刷新计时器
  void refreshChronometer() {
    if (_isTimerRunning) {
      _updateElapsedTime();
      notifyListeners();
    }
  }

  /// 格式化时间显示
  String formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return '${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds';
  }

  /// 选择开始图片
  Future<void> selectStartImage(BuildContext context) async {
    if (!_checkUserLogin(context)) return;

    if (hasActiveQuest) {
      MagmaToast.warning(
        context,
        title: 'You already have an active challenge',
      );
      return;
    }

    try {
      await showDialog(
        context: context,
        builder:
            (context) => GalleryMediaPicker(
              pathList: (List<PickedAssetModel> paths) async {
                if (paths.isNotEmpty) {
                  final imagePath = await _saveImageToLocal(
                    paths.first,
                    context,
                  );
                  if (imagePath != null) {
                    _startImagePath = imagePath;
                    await _beginQuest(context);
                    Navigator.of(context).pop();
                  }
                }
              },
              appBarLeadingWidget: Icon(Icons.close),
              mediaPickerParams: MediaPickerParamsModel(
                appBarHeight: 50,
                maxPickImages: 1,
                crossAxisCount: 3,
                childAspectRatio: .5,
                singlePick: true,
                appBarColor: Colors.black,
                gridViewBgColor: Colors.black,
                albumTextColor: Colors.white,
                gridPadding: EdgeInsets.zero,
                thumbnailBgColor: Colors.grey,
                thumbnailBoxFix: BoxFit.cover,
                selectedAlbumIcon: Icons.check,
                selectedCheckColor: Colors.white,
                albumSelectIconColor: Colors.blue,
                selectedCheckBgColor: Colors.blue,
                selectedAlbumBgColor: Colors.black,
                albumDropDownBgColor: Colors.grey,
                albumSelectTextColor: Colors.white,
                selectedAssetBgColor: Colors.blue,
                selectedAlbumTextColor: Colors.white,
                mediaType: GalleryMediaType.onlyImages,
                gridViewController: ScrollController(),
                thumbnailQuality: ThumbnailQuality.medium,
                gridViewPhysics: const BouncingScrollPhysics(),
              ),
            ),
      );
    } catch (e) {
      MagmaToast.error(context, title: 'Failed to select image: $e');
    }
  }

  /// 选择结束图片
  Future<void> selectEndImage(BuildContext context) async {
    if (!_checkUserLogin(context)) return;

    if (!hasActiveQuest || _startImagePath == null) {
      MagmaToast.warning(context, title: 'Please upload start image first');
      return;
    }

    try {
      await showDialog(
        context: context,
        builder:
            (context) => GalleryMediaPicker(
              pathList: (List<PickedAssetModel> paths) async {
                if (paths.isNotEmpty) {
                  final imagePath = await _saveImageToLocal(
                    paths.first,
                    context,
                  );
                  if (imagePath != null) {
                    _endImagePath = imagePath;
                    await _finishQuest(context);
                    Navigator.of(context).pop();
                  }
                }
              },
              appBarLeadingWidget: Icon(Icons.close),
              mediaPickerParams: MediaPickerParamsModel(
                appBarHeight: 50,
                maxPickImages: 1,
                crossAxisCount: 3,
                childAspectRatio: .5,
                singlePick: true,
                appBarColor: Colors.black,
                gridViewBgColor: Colors.black,
                albumTextColor: Colors.white,
                gridPadding: EdgeInsets.zero,
                thumbnailBgColor: Colors.grey,
                thumbnailBoxFix: BoxFit.cover,
                selectedAlbumIcon: Icons.check,
                selectedCheckColor: Colors.white,
                albumSelectIconColor: Colors.blue,
                selectedCheckBgColor: Colors.blue,
                selectedAlbumBgColor: Colors.black,
                albumDropDownBgColor: Colors.grey,
                albumSelectTextColor: Colors.white,
                selectedAssetBgColor: Colors.blue,
                selectedAlbumTextColor: Colors.white,
                mediaType: GalleryMediaType.all,
                gridViewController: ScrollController(),
                thumbnailQuality: ThumbnailQuality.medium,
                gridViewPhysics: const BouncingScrollPhysics(),
              ),
            ),
      );
    } catch (e) {
      MagmaToast.error(context, title: 'Failed to select image: $e');
    }
  }

  /// 保存图片到本地
  Future<String?> _saveImageToLocal(
    PickedAssetModel pickedAsset,
    BuildContext context,
  ) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final questDir = Directory(path.join(directory.path, 'quest_images'));
      if (!await questDir.exists()) {
        await questDir.create(recursive: true);
      }

      final fileName = '${DateTime.now().millisecondsSinceEpoch}.jpg';
      final filePath = path.join(questDir.path, fileName);
      final file = File(filePath);

      final bytes = await pickedAsset.file!.readAsBytes();
      await file.writeAsBytes(bytes);
      return filePath;
    } catch (e) {
      MagmaToast.error(context, title: 'Failed to save image: $e');
      return null;
    }
  }

  /// 开始挑战
  Future<void> _beginQuest(BuildContext context) async {
    if (_currentQuest == null) return;

    setBusy(true);
    try {
      final success = await appState.questManager.beginQuest(
        _currentQuest!.id,
        'current_user',
      );
      if (success) {
        _activeAttempt = appState.questManager.activeAttempt;
        _chronometerStart = DateTime.now();
        _isTimerRunning = true;
        await appState.questManager.submitStartImage(_startImagePath!);
        MagmaToast.success(context, title: 'Challenge started successfully!');
        startTimer();
      }
    } catch (e) {
      MagmaToast.error(context, title: 'Failed to start challenge');
    } finally {
      setBusy(false);
      notifyListeners();
    }
  }

  /// 完成挑战
  Future<void> _finishQuest(BuildContext context) async {
    if (_endImagePath == null) return;

    setBusy(true);
    try {
      final success = await appState.questManager.finishQuest(_endImagePath!);
      if (success) {
        _isTimerRunning = false;
        timer?.cancel();

        // 重新加载挑战状态以反映完成状态
        _loadExistingAttempt();

        MagmaToast.success(context, title: 'Challenge completed successfully!');
      }
    } catch (e) {
      MagmaToast.error(context, title: 'Failed to complete challenge');
    } finally {
      setBusy(false);
      notifyListeners();
    }
  }

  /// 检查用户登录状态
  bool _checkUserLogin(BuildContext context) {
    // 检查用户是否已登录
    bool isLoggedIn = appState.userStore.isLoggedIn;

    if (!isLoggedIn) {
      LoginRequiredDialog.show(
        context,
        title: 'Authentication Required',
        message: 'Please log in to upload images and start challenges.',
        confirmText: 'Login',
        cancelText: 'Cancel',
      );
      return false;
    }
    return true;
  }

  /// 显示提示信息
  void showToast(BuildContext context, String message, {String? description}) {
    MagmaToast.info(context, title: message, description: description);
  }

  /// 启动定时器
  void startTimer() {
    timer?.cancel();
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_isTimerRunning) {
        refreshChronometer();
      } else {
        timer.cancel();
      }
    });
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }
}

/// 挑战详情页面
class QuestDetailStory extends StatelessWidget {
  final String questId;

  const QuestDetailStory({super.key, required this.questId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<QuestDetailNavigatorViewModel>.reactive(
      viewModelBuilder:
          () => QuestDetailNavigatorViewModel()..initializeQuestDetail(questId),
      onModelReady: (viewModel) {
        // 确保计时器在页面加载完成后启动
        if (viewModel.isTimerRunning && viewModel.timer == null) {
          viewModel.startTimer();
        }
      },
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: SafeArea(
            bottom: false,
            child: Column(
              children: [
                // 顶部导航栏
                _constructNavigationBar(context),
                // 可滚动内容
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        SizedBox(height: 24.h),
                        // 挑战信息卡片
                        _buildQuestInfoCard(viewModel),
                        SizedBox(height: 16.h),
                        // 挑战说明
                        _buildQuestInstructions(),
                        SizedBox(height: 16.h),
                        _buildEulaText(),
                        SizedBox(height: 16.h),
                        // 挑战按钮
                        _buildChallengeButton(viewModel, context),
                        SizedBox(height: 32.h),
                        // 图片上传区域
                        _buildImageUploadSection(viewModel, context),
                        SizedBox(height: 32.h), // 底部额外间距
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建导航栏
  Widget _constructNavigationBar(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
        top: 16.h,
        bottom: 16.h,
      ),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => QR.back(),
            child: Image.asset(MagmaConstant.back, width: 20.w, height: 25.w),
          ),
          Spacer(),
          Text(
            'Challenge Details',
          ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
          Spacer(),
          SizedBox(width: 20.w),
        ],
      ),
    );
  }

  /// 构建挑战信息卡片
  Widget _buildQuestInfoCard(QuestDetailNavigatorViewModel viewModel) {
    final quest = viewModel.currentQuest!;
    final questIndex = viewModel.getQuestIndex(quest.id);

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 挑战信息卡片主体
          AspectRatio(
            aspectRatio: 371 / 316,
            child: Container(
              padding: EdgeInsets.all(12.w),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(MagmaConstant.challengeDetailCard),
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(2.r),
              ),
              child: Column(
                children: [
                  // 挑战图片
                  AspectRatio(
                    aspectRatio: 350 / 235,
                    child: ClipRRect(
                      child: Image.asset(
                        quest.image,
                        fit: BoxFit.cover,
                        width: double.infinity,
                      ),
                    ),
                  ),
                  SizedBox(height: 12.h),
                  // 挑战详情
                  SizedBox(
                    width: double.infinity,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        // 距离信息
                        RichText(
                          textAlign: TextAlign.left,
                          text: TextSpan(
                            children: [
                              TextSpan(
                                text: 'Total Distance: ',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: MagmaColor.grey,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                              TextSpan(
                                text: '${quest.distance} Kilometers',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: MagmaColor.black,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(height: 8.h),
                        // 时间限制信息
                        RichText(
                          textAlign: TextAlign.left,
                          text: TextSpan(
                            children: [
                              TextSpan(
                                text: 'Completion Time Limit: ',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: MagmaColor.grey,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                              TextSpan(
                                text:
                                    '${quest.minTime}-${quest.maxTime} Minutes',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: MagmaColor.black,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          // 挑战标签 - 定位在卡片上边框
          Positioned(
            top: -23.h,
            left: 60.w,
            right: 60.w,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              decoration: BoxDecoration(
                color: const Color(0xFFF0E9F9),
                borderRadius: BorderRadius.circular(22.5.r),
                border: Border.all(color: MagmaColor.black, width: 1.w),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    width: 32.w,
                    height: 32.w,
                    decoration: BoxDecoration(
                      color: MagmaColor.purple,
                      shape: BoxShape.circle,
                    ),
                    child: Center(
                      child: Text('${questIndex + 1}').blackHanSans(
                        fontSize: 18.sp,
                        color: MagmaColor.black,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                  SizedBox(width: 8.w),
                  Text(quest.title).blackHanSans(
                    fontSize: 14.sp,
                    color: MagmaColor.black,
                    fontWeight: FontWeight.w400,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建挑战说明
  Widget _buildQuestInstructions() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Text(
        'You need to upload pictures of the starting and ending points of the challenge to complete the challenge.',
        textAlign: TextAlign.center,
        style: TextStyle(height: 1.46),
      ).inter(
        fontSize: 13.sp,
        color: Colors.white.withValues(alpha: 0.50),
        fontWeight: FontWeight.w400,
      ),
    );
  }

  Widget _buildEulaText() {
    return GestureDetector(
      onTap: () {
        MagmaUrl.openUrl(MagmaConstant.eulaUrl);
      },
      child: Text(
        'EULA',
        textAlign: TextAlign.center,
        style: TextStyle(
          color: Colors.white,
          fontSize: 13.sp,
          fontWeight: FontWeight.w600,
          decoration: TextDecoration.underline,
          decorationColor: MagmaColor.white,
        ),
      ),
    );
  }

  /// 构建挑战按钮
  Widget _buildChallengeButton(
    QuestDetailNavigatorViewModel viewModel,
    BuildContext context,
  ) {
    // 检查是否有已完成的挑战
    final hasCompletedAttempt =
        viewModel.activeAttempt != null && viewModel.activeAttempt!.isCompleted;

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: SizedBox(
        width: double.infinity,
        child: ElevatedButton(
          onPressed:
              hasCompletedAttempt || viewModel.isBusy
                  ? () {
                    // 已完成或忙碌时，显示提示信息
                    if (hasCompletedAttempt) {
                      MagmaToast.info(
                        context,
                        title: 'Challenge already completed',
                      );
                    }
                  }
                  : () {
                    // 挑战按钮点击逻辑
                    if (viewModel.startImagePath == null) {
                      // 如果还没有开始图片，提示用户上传开始图片
                      MagmaToast.warning(
                        context,
                        title: 'Please upload start image first',
                      );
                    } else if (viewModel.endImagePath == null &&
                        !viewModel.isTimerRunning) {
                      // 如果已经开始但还没结束，提示用户上传结束图片
                      MagmaToast.warning(
                        context,
                        title: 'Please upload end image to complete challenge',
                      );
                    }
                  },
          style: ElevatedButton.styleFrom(
            backgroundColor: MagmaColor.purple,
            padding: EdgeInsets.symmetric(vertical: 16.h),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12.r),
            ),
          ),
          child: _buildButtonContent(viewModel),
        ),
      ),
    );
  }

  /// 构建按钮内容
  Widget _buildButtonContent(QuestDetailNavigatorViewModel viewModel) {
    // 检查是否有已完成的挑战
    final hasCompletedAttempt =
        viewModel.activeAttempt != null && viewModel.activeAttempt!.isCompleted;

    if (hasCompletedAttempt) {
      // 显示已完成状态和完成时间
      final duration = viewModel.activeAttempt!.duration ?? Duration.zero;
      final hours = duration.inHours;
      final minutes = duration.inMinutes.remainder(60);
      final seconds = duration.inSeconds.remainder(60);

      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('Challenge Completed').blackHanSans(
            fontSize: 18.sp,
            color: MagmaColor.black,
            fontWeight: FontWeight.w600,
          ),
          SizedBox(height: 4.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildAnimatedDigit(hours, 2),
              Text(':').blackHanSans(
                fontSize: 18.sp,
                color: MagmaColor.black,
                fontWeight: FontWeight.w600,
              ),
              _buildAnimatedDigit(minutes, 2),
              Text(':').blackHanSans(
                fontSize: 18.sp,
                color: MagmaColor.black,
                fontWeight: FontWeight.w600,
              ),
              _buildAnimatedDigit(seconds, 2),
            ],
          ),
        ],
      );
    } else if (viewModel.isTimerRunning) {
      // 使用 AnimatedDigitWidget 显示计时器
      final duration = viewModel.elapsedDuration;
      final hours = duration.inHours;
      final minutes = duration.inMinutes.remainder(60);
      final seconds = duration.inSeconds.remainder(60);

      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          _buildAnimatedDigit(hours, 2),
          Text(':').blackHanSans(
            fontSize: 24.sp,
            color: MagmaColor.black,
            fontWeight: FontWeight.w600,
          ),
          _buildAnimatedDigit(minutes, 2),
          Text(':').blackHanSans(
            fontSize: 24.sp,
            color: MagmaColor.black,
            fontWeight: FontWeight.w600,
          ),
          _buildAnimatedDigit(seconds, 2),
        ],
      );
    } else if (viewModel.startImagePath != null &&
        viewModel.endImagePath == null) {
      return Text('Upload End Image').blackHanSans(
        fontSize: 24.sp,
        color: MagmaColor.black,
        fontWeight: FontWeight.w600,
      );
    } else if (viewModel.startImagePath == null) {
      return Text('Start Challenge').blackHanSans(
        fontSize: 24.sp,
        color: MagmaColor.black,
        fontWeight: FontWeight.w600,
      );
    } else {
      return Text('Challenge').blackHanSans(
        fontSize: 24.sp,
        color: MagmaColor.black,
        fontWeight: FontWeight.w600,
      );
    }
  }

  /// 构建单个数字的动画
  Widget _buildAnimatedDigit(int value, int digits) {
    return AnimatedDigitWidget(
      value: value.toDouble(),
      duration: const Duration(milliseconds: 500),
      textStyle: TextStyle(
        fontSize: 24.sp,
        color: MagmaColor.black,
        fontWeight: FontWeight.w600,
        fontFamily: 'BlackHanSans',
      ),
      fractionDigits: 0,
      enableSeparator: false,
      prefix: '',
      suffix: '',
    );
  }

  /// 构建图片上传区域
  Widget _buildImageUploadSection(
    QuestDetailNavigatorViewModel viewModel,
    BuildContext context,
  ) {
    // 检查是否有已完成的挑战
    final hasCompletedAttempt =
        viewModel.activeAttempt != null && viewModel.activeAttempt!.isCompleted;

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          // 开始图片上传
          _buildImageUploadBox(
            label: 'start',
            imagePath: viewModel.startImagePath,
            onTap:
                hasCompletedAttempt
                    ? null // 已完成时不允许点击
                    : () => viewModel.selectStartImage(context),
            isCompleted: hasCompletedAttempt,
          ),
          SizedBox(height: 24.h),
          // 结束图片上传
          _buildImageUploadBox(
            label: 'end',
            imagePath: viewModel.endImagePath,
            onTap:
                hasCompletedAttempt
                    ? null // 已完成时不允许点击
                    : () => viewModel.selectEndImage(context),
            isCompleted: hasCompletedAttempt,
          ),
        ],
      ),
    );
  }

  /// 构建图片上传框
  Widget _buildImageUploadBox({
    required String label,
    String? imagePath,
    VoidCallback? onTap,
    bool isCompleted = false,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(label).blackHanSans(
              fontSize: 18.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w600,
            ),
            if (isCompleted) ...[
              SizedBox(width: 8.w),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.h),
                decoration: BoxDecoration(
                  color: Colors.green,
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text(
                  'Completed',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ],
        ),
        SizedBox(height: 12.h),
        GestureDetector(
          onTap: onTap,
          child: AspectRatio(
            aspectRatio: 374 / 242,
            child: Container(
              decoration: BoxDecoration(
                border: DashedBorder.all(
                  color: isCompleted ? Colors.green : MagmaColor.white,
                  width: 1.w,
                  dashLength: 6.w,
                  spaceLength: 6.w,
                ),
                borderRadius: BorderRadius.circular(2.r),
              ),
              child: Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  color: MagmaColor.black,
                  borderRadius: BorderRadius.circular(2.r),
                ),
                child:
                    imagePath != null
                        ? Stack(
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(2.r),
                              child: Image.file(
                                File(imagePath),
                                width: double.infinity,
                                height: double.infinity,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ],
                        )
                        : Center(
                          child: Image.asset(
                            MagmaConstant.upload,
                            width: 28.w,
                            height: 28.w,
                          ),
                        ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
